package com.zzhou.linkinfo.clock.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.suke.widget.SwitchButton;
import com.zzhou.linkinfo.clock.customview.ClockReleaseCycleSelectDialog;
import com.zzhou.linkinfo.clock.R;
import com.zzhou.linkinfo.clock.util.Utils;
import com.zzhou.linkinfo.clock.activity.base.AbstractTitleActivity;
import com.zzhou.linkinfo.clock.adapter.ClockShowPicsAdapter;
import com.zzhou.linkinfo.clock.entity.ClockFrequency;
import com.zzhou.linkinfo.clock.entity.Group;
import com.zzhou.linkinfo.clock.entity.Person;
import com.zzhou.linkinfo.clock.util.ToastShow;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Clock release task.
 * Created by The Carlos on 2019/3/14.
 */
public class ClockReleaseTaskActivity extends AbstractTitleActivity {
    private static final int MAX_CONTENT_LENGTH = 500; // 最长输入文本长度
    private static final int MAX_SELECTED_PIC_COUNT = 9; // 最长支持可选图片数量
    private static final int REQUEST_RECEIVER = 1;
    private static final int REQUEST_FREQUENCY = 2;

    private TextView mSelectedReceiver;
    private Button mSelectReceiverIcon;
    private EditText mTaskSubject;
    private EditText mTaskDescribe;
    private TextView mLeftContentCount;
    private LinearLayout mRecordVoiceLayout;
    private ImageView mCancelVoice;
    private TextView mRecordVoiceTime;
    private TextView mReRecordVoice;
    private RecyclerView mPicsRecyclerView;
    private TextView mRecordVoice;
    private TextView mSelectPic;
    private TextView mTaskCycle;
    private Button mTaskCycleBtn;
    private TextView mTaskFrequency;
    private Button mTaskFrequencyBtn;
    private SwitchButton mSwitchBtn;

    private ArrayList<Group> mChosenReceivers;
    private ArrayList<ClockFrequency> mChosenClockFrequency;

    private boolean mIsVisible; // 是否相互可见
    private boolean mIsOpenedSmsRemind; // 是否开启短信提醒

    private int mChoosePicThemeId;
    private List<LocalMedia> mSelectedPicsList = new ArrayList<>();
    private List<LocalMedia> mSelectedAudioList = new ArrayList<>();
    private ClockShowPicsAdapter mResAdapter;
    private int mChooseMode = PictureMimeType.ofAudio();
    private static final int AUDIO_REQUEST_CODE = 200;

    private int mCurrentCycleItem = 0;

    @Override
    protected int attachLayoutRes() {
        return R.layout.clock_activity_release_task;
    }

    @Override
    protected void initView() {
        mSelectedReceiver = findViewById(R.id.selected_parent);
        mSelectReceiverIcon = findViewById(R.id.receiver_select_icon);
        mTaskSubject = findViewById(R.id.task_subject);
        mTaskDescribe = findViewById(R.id.task_describe);
        mLeftContentCount = findViewById(R.id.left_content_count);
        mRecordVoiceLayout = findViewById(R.id.record_voice_layout);
        mCancelVoice = findViewById(R.id.voice_delete_button);
        mRecordVoiceTime = findViewById(R.id.voice_time);
        mReRecordVoice = findViewById(R.id.re_record);
        mPicsRecyclerView = findViewById(R.id.selected_pics_recycler_view);
        mRecordVoice = findViewById(R.id.record_voice_icon);
        mSelectPic = findViewById(R.id.select_pic_icon);
        mTaskCycle = findViewById(R.id.task_cycle);
        mTaskCycleBtn = findViewById(R.id.edit_task_cycle);
        mTaskFrequency = findViewById(R.id.task_frequency);
        mTaskFrequencyBtn = findViewById(R.id.edit_task_frequency);
        mSwitchBtn = findViewById(R.id.checkbox_status);

        mLeftContentCount.setText(String.format(getString(R.string.clock_release_task_left_text_count), 0));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mPicsRecyclerView.setLayoutManager(layoutManager);

        mChoosePicThemeId = R.style.picture_default_style;
        mResAdapter = new ClockShowPicsAdapter(ClockReleaseTaskActivity.this, onAddPicClickListener);
        mResAdapter.setList(mSelectedPicsList);
        mResAdapter.setSelectMax(MAX_SELECTED_PIC_COUNT);
        mPicsRecyclerView.setAdapter(mResAdapter);
        mResAdapter.setOnItemClickListener(new ClockShowPicsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (mSelectedPicsList.size() > 0) {
                    LocalMedia media = mSelectedPicsList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).themeStyle(mChoosePicThemeId).externalPicturePreview(position, "/custom_file", mSelectedPicsList);
                            PictureSelector.create(ClockReleaseTaskActivity.this).themeStyle(mChoosePicThemeId).openExternalPreview(position, mSelectedPicsList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(ClockReleaseTaskActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(ClockReleaseTaskActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });

        setListener();
    }

    private void checkPermission(final int chooseMode, final int selectionMode, final List<LocalMedia> localMediaList, final int requestCode) {
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(ClockReleaseTaskActivity.this);
                    addPicture(chooseMode, selectionMode, localMediaList, requestCode);
                } else {
                    Toast.makeText(ClockReleaseTaskActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void setListener() {

        mTaskDescribe.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int editStart;
            private int editEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                temp = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                editStart = mTaskDescribe.getSelectionStart();
                editEnd = mTaskDescribe.getSelectionEnd();

                if (temp.length() > MAX_CONTENT_LENGTH) {
                    Toast.makeText(ClockReleaseTaskActivity.this, R.string.clock_release_task_input_limit, Toast.LENGTH_SHORT).show();
                    s.delete(editStart - 1, editEnd);
                    int tempSelection = editStart;
                    mTaskDescribe.setText(s);
                    mTaskDescribe.setSelection(tempSelection);
                } else {
                    mLeftContentCount.setText(String.format(getString(R.string.clock_release_task_left_text_count), s.length()));
                }
            }
        });

        mSelectReceiverIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ClockReleaseTaskActivity.this,
                        ClockSelectContactsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(ClockSelectContactsActivity.CHOSEN_RECEIVERS, mChosenReceivers);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_RECEIVER);
            }
        });

        mCancelVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRecordVoiceLayout.setVisibility(View.GONE);
                mSelectedAudioList.clear();
            }
        });

        mRecordVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRecordVoiceLayout.setVisibility(View.GONE);
                mSelectedAudioList.clear();
                checkPermission(PictureMimeType.ofAudio(), PictureConfig.SINGLE, mSelectedAudioList, AUDIO_REQUEST_CODE);
            }
        });

        mReRecordVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRecordVoiceLayout.setVisibility(View.GONE);
                mSelectedAudioList.clear();
                checkPermission(PictureMimeType.ofAudio(), PictureConfig.SINGLE, mSelectedAudioList, AUDIO_REQUEST_CODE);
            }
        });

        mSelectPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectedPicsList.size() < MAX_SELECTED_PIC_COUNT) {
                    checkPermission(PictureMimeType.ofImage(), PictureConfig.MULTIPLE, mSelectedPicsList, PictureConfig.CHOOSE_REQUEST);
                } else {
                    Toast.makeText(ClockReleaseTaskActivity.this,
                            R.string.clock_release_task_selected_pics_limit, Toast.LENGTH_SHORT).show();
                }
            }
        });

        mTaskCycleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new ClockReleaseCycleSelectDialog(ClockReleaseTaskActivity.this, mCurrentCycleItem,
                        new ClockReleaseCycleSelectDialog.IOnClickListener() {
                            @Override
                            public void save(String selectedCycle, int currentItem) {
                                mCurrentCycleItem = currentItem;
                                mTaskCycle.setText(String.format(getString(R.string.clock_release_task_cycle_value), selectedCycle));
                            }
                        }).show();
            }
        });

        mTaskFrequencyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ClockReleaseTaskActivity.this,
                        ClockFrequencyActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(ClockFrequencyActivity.CHOSEN_FREQUENCY, mChosenClockFrequency);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_FREQUENCY);
            }
        });

        mSwitchBtn.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                ToastShow.show(ClockReleaseTaskActivity.this, isChecked ? "Opened" : "Closed");
            }
        });
    }

    private ClockShowPicsAdapter.IAddPicClickListener onAddPicClickListener = new ClockShowPicsAdapter.IAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            boolean mode = true;
            if (mode) {
                addPicture(PictureMimeType.ofImage(), PictureConfig.SINGLE, mSelectedPicsList, PictureConfig.CHOOSE_REQUEST);
            } else {
            }
        }

        @Override
        public void updateMainView() {
            if (mSelectedPicsList.size() > 0) {
                mPicsRecyclerView.setVisibility(View.VISIBLE);
            } else {
                mPicsRecyclerView.setVisibility(View.GONE);
            }
        }

    };

    private void addPicture(int chooseMode, int selectionMode, List<LocalMedia> localMediaList, int requestCode) {
        if (chooseMode == PictureMimeType.ofAudio()) {
            PictureSelector.create(ClockReleaseTaskActivity.this)
                    .openCamera(PictureMimeType.ofAudio())
                    .forResult(AUDIO_REQUEST_CODE);
        } else {
            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(ClockReleaseTaskActivity.this)
                    .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(mChoosePicThemeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(MAX_SELECTED_PIC_COUNT)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(selectionMode)
                    .previewImage(true)// 是否可预览图片
                    .previewVideo(true)// 是否可预览视频
                    .enablePreviewAudio(true) // 是否可播放音频
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
//                        .enableCrop(cb_crop.isChecked())// 是否裁剪
//                        .compress(cb_compress.isChecked())// 是否压缩
                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    //.compressSavePath(getPath())//压缩图片保存地址
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                        .withAspectRatio(aspect_ratio_x, aspect_ratio_y)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                        .hideBottomControls(cb_hide.isChecked() ? false : true)// 是否显示uCrop工具栏，默认不显示
//                        .isGif(cb_isGif.isChecked())// 是否显示gif图片
                    .isGif(true)// 是否显示gif图片
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
//                        .circleDimmedLayer(cb_crop_circular.isChecked())// 是否圆形裁剪
//                        .showCropFrame(cb_showCropFrame.isChecked())// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
//                        .showCropGrid(cb_showCropGrid.isChecked())// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
//                        .openClickSound(cb_voice.isChecked())// 是否开启点击声音
                    .selectionMedia(localMediaList)// 是否传入已选图片
                    //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                    //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.rotateEnabled(true) // 裁剪是否可旋转图片
                    //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                    //.videoQuality()// 视频录制质量 0 or 1
                    //.videoSecond()//显示多少秒以内的视频or音频也可适用
                    //.recordVideoSecond()//录制视频秒数 默认60s
                    .forResult(requestCode);//结果回调onActivityResult code
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    mSelectedPicsList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    for (LocalMedia media : mSelectedAudioList) {
                        Log.i("图片-----》", media.getPath());
                    }
                    if (mSelectedPicsList.size() > 0) {
                        mPicsRecyclerView.setVisibility(View.VISIBLE);
                    } else {
                        mPicsRecyclerView.setVisibility(View.GONE);
                    }

                    mResAdapter.setList(mSelectedPicsList);
                    mResAdapter.notifyDataSetChanged();
                    break;

                case AUDIO_REQUEST_CODE:
                    mSelectedAudioList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : mSelectedAudioList) {
                        Log.i("图片-----》", media.getPath());
                        if (media.getMimeType() == PictureMimeType.ofAudio()) {
                            mRecordVoiceLayout.setVisibility(View.VISIBLE);
                            mRecordVoiceTime.setText(Utils.timeParse(media.getDuration()));
                        }
                    }
                    break;
                case REQUEST_RECEIVER:
                    if (data != null) {
                        mChosenReceivers = (ArrayList<Group>) data
                                .getExtras()
                                .getSerializable(ClockSelectContactsActivity.RECEIVER_RESULT);
                        mSelectedReceiver
                                .setText(getCaptionByChooseReceiver(mChosenReceivers));
                    }
                    break;

                case REQUEST_FREQUENCY:
                    if (data != null) {
                        mIsOpenedSmsRemind = data.getExtras().getBoolean(ClockFrequencyActivity.SMS_REMIND_RESULT);
                        mChosenClockFrequency = (ArrayList<ClockFrequency>) data
                                .getExtras()
                                .getSerializable(ClockFrequencyActivity.FREQUENCY_RESULT);

                        mTaskFrequency.setText(getFinalFrequencyContent(mChosenClockFrequency));
                    }

                    break;
            }
        }
    }

    /**
     * 获取最终选择的打开频次显示文本
     *
     * @param frequencies
     * @return
     */
    private String getFinalFrequencyContent(List<ClockFrequency> frequencies) {
        if (frequencies != null && frequencies.size() > 0) {
            StringBuffer sb = new StringBuffer();
            // 展示文本从周一的item开始
            for (int i = 3; i < frequencies.size(); i++) {
                if (frequencies.get(i).isSelected()) {
                    sb.append(frequencies.get(i).getName(), 1, frequencies.get(i).getName().length());
                    sb.append(" ");
                }
            }
            String s = sb.toString();
            if (s.length() > 0) {
                s = s.substring(0, s.length() - 1);
            }
            return s;
        }
        return "";
    }

    /**
     * 获取选择的接收人的显示文本
     *
     * @param groups
     * @return
     */
    private String getCaptionByChooseReceiver(ArrayList<Group> groups) {
        if (groups != null && groups.size() > 0) {
            StringBuffer sb = new StringBuffer();
            for (Group group : groups) {
                if (group.isChecked()) {
                    sb.append(group.getName());
                    sb.append(",");
                } else {
                    List<Person> persons = group.getPersons();
                    if (persons != null && persons.size() > 0) {
                        for (Person p : persons) {
                            if (p.isChecked()) {
                                sb.append(p.getName());
                                sb.append(",");
                            }
                        }
                    }
                }
            }
            String s = sb.toString();
            if (s.length() > 0) {
                s = s.substring(0, s.length() - 1);
            }
            return s;
        }
        return "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mTaskDescribe.getWindowToken(), 0); //强制隐藏键盘
    }
}
